package corp.sunny.frameworks.session;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import corp.sunny.commons.util.security.JAASPrincipal;
import corp.sunny.commons.util.security.JAASSerializer;
import corp.sunny.commons.util.security.JAASSerializerException;
import corp.sunny.frameworks.exception.ComponentFailureException;

/**
 * @File:SessionInitializer.java
 * @Date:Jul 6, 2011
 * @Author:Subhash Bavi
 * 
 * @Description:
 * @Copyright Sunny Corporation - 2011
 */
public class SessionInitializer {

	protected HttpSession httpSession;
	protected HttpServletRequest httpServletRequest;
	protected HttpServletResponse httpServletResponse;

	// Namespaces. Only child classed allowed to access these variables
	protected final String IS_AUTHENTICATED = "IS_AUTHENTICATED";
	protected final String SECURE_SESSION = "SECURE_SESSION";
	protected final String JAAS_PRINCPAL = "JAAS_PRINCPAL";

	private Logger LOG = Logger.getLogger(SessionInitializer.class);

	/**
	 * Initializes the session from the request, response objects
	 * 
	 * @param request
	 * @param response
	 */
	protected void initializeSession(ServletRequest request,
			ServletResponse response) throws ComponentFailureException {

		String secureSession = null;
		Boolean isAuthenticated;
		JAASPrincipal jaasPrincipal;

		httpServletRequest = (HttpServletRequest) request;
		httpServletResponse = (HttpServletResponse) response;

		// Get the JAASPrincipal object from the session
		httpSession = (HttpSession) httpServletRequest.getSession(false);
		secureSession = (String) httpSession.getAttribute(SECURE_SESSION);

		isAuthenticated = (null == secureSession) ? Boolean.TRUE
				: Boolean.FALSE;

		LOG.info("User Authentication :: " + isAuthenticated);
		httpServletRequest.setAttribute(IS_AUTHENTICATED, isAuthenticated);

		// Get the JAASPrincipal
		if (!isAuthenticated) {
			try {
				jaasPrincipal = (JAASPrincipal) JAASSerializer
						.getDeSerializedObject(secureSession);
				httpServletRequest.setAttribute(JAAS_PRINCPAL, jaasPrincipal);
			} catch (JAASSerializerException e) {
				LOG.fatal(e);
				LOG.error("Failed to initialize the JAASPrincipal", e);
				throw new ComponentFailureException(
						"JAASPRINCIPAL_CREATION_FAILURE", e.getMessage());
			}
		}// End of if()
	}// End of method
}
